---
import Icon from '../Icon.astro';
import Spinner from '../Spinner.astro';
---

<button
  class='inline-flex h-10 w-full items-center justify-center rounded border border-slate-300 bg-white p-2 text-sm font-medium text-black outline-none transition duration-150 ease-in-out focus:ring-2 focus:ring-[#333] focus:ring-offset-1 disabled:opacity-60 disabled:cursor-not-allowed'
  id='google-login-button'
>
  <Spinner class='hidden text-black' data-google-login-spinner />
  <div class='flex items-center' data-google-text>
    <Icon icon='google' />
    <span class='ml-2'>Continue with Google</span>
  </div>
</button>

<p class='hidden text-sm font-medium text-red-600' data-google-error></p>

<script>
  import Cookies from 'js-cookie';
  import { TOKEN_COOKIE_NAME } from '../../lib/constants';
  const googleLoginButton = document.getElementById('google-login-button');
  const googleLoginSpinner = document.querySelector(
    '[data-google-login-spinner]'
  );
  const googleLoginText = document.querySelector('[data-google-text]');
  const googleErrorText = document.querySelector('[data-google-error]');

  function addSpinner() {
    googleLoginText?.classList.add('hidden');
    googleLoginSpinner?.classList.remove('hidden');
    // Disable button
    googleLoginButton?.setAttribute('disabled', 'true');
  }

  function hideSpinner() {
    googleLoginText?.classList.remove('hidden');
    googleLoginSpinner?.classList.add('hidden');
    // Enable button
    googleLoginButton?.setAttribute('disabled', 'true');
  }

  function showError(err: Error) {
    googleErrorText?.classList.remove('hidden');
    if (googleErrorText) {
      googleErrorText.innerHTML = err.message;
    }
  }

  googleLoginButton?.addEventListener('click', () => {
    // Show spinner
    addSpinner();

    fetch('http://localhost:8080/v1-google-login', {
      credentials: 'include',
    })
      .then((res) => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('Something went wrong.');
        }
      })
      .then((data) => {
        // Redirect to google login
        if (data.loginUrl) {
          window.location.href = data.loginUrl;
        } else {
          // Else throw error
          throw new Error('Something went wrong.');
        }
      })
      .catch((err: Error) => {
        hideSpinner();

        // Show error in the UI
        showError(err);
      });
  });

  window.addEventListener('load', () => {
    // Get all query params and send them to v1-google-callback
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    const state = urlParams.get('state');
    const prompt = urlParams.get('prompt');
    const provider = urlParams.get('provider');

    if (code && state && prompt && provider === 'google') {
      // Show spinner
      addSpinner();

      fetch(
        `http://localhost:8080/v1-google-callback${window.location.search}`,
        {
          method: 'GET',
          credentials: 'include',
        }
      )
        .then((res) => {
          if (res.ok) {
            return res.json();
          } else {
            throw new Error('Something went wrong.');
          }
        })
        .then((data) => {
          // Remove spinner
          hideSpinner();

          // Set token in cookie and redirect to home
          if (data.token) {
            Cookies.set(TOKEN_COOKIE_NAME, data.token);

            // Redirect to the page the user was on before login
            history.go(-2);
          } else {
            throw new Error('Something went wrong.');
          }
        })
        .catch((err: Error) => {
          hideSpinner();
          showError(err);
        });
    }
  });
</script>
